package com.ruoyi.web.config;
//

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.ruoyi.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.ruoyi.common.utils.file.FileUtils.File2byte;


@Slf4j
@Configuration
public class OSSClientUtil_local {

    private static String endpoint = "http://oss-cn-hangzhou-zjyc-d01-a.ops.cloud.zj.yc";
    private static String accessKeyId = "Pqp7jTPy8bG2bAn8";

    private static String accessKeySecret = "Ro7fCkBzsvr0cnV5d5RWVIKap4dMSo";

    private static String filedir = "";

    private static String bucketName = "oss-tpia-seal-pro";

    private static OSS ossClient;

    public static void main(String[] args) throws FileNotFoundException {
        long l1 = System.currentTimeMillis();
        init();
//        list();
        uploadFile2OSS(FileUtils.file2InputStream(new File("D:\\测试样例.pdf")),"sssss","pdf");
        long l2 = System.currentTimeMillis();
        System.out.println(l2-l1);
        shutdown();
    }

    /**
     * 初始化
     */
    public static void init() {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        /* 通过一个Bucket对象来创建 */
        CreateBucketRequest bucketObj = new CreateBucketRequest(null);// 构造函数入参为Bucket名称，可以为空
        bucketObj.setBucketName(bucketName);// 设置bucketObj名称
        bucketObj.setCannedACL(CannedAccessControlList.PublicReadWrite);// 设置bucketObj访问权限acl
        ossClient.createBucket(bucketObj);// 创建Bucket
    }

    /**
     * 销毁
     */
    public static void shutdown() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     * @param inStream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public static boolean uploadFile2OSS(InputStream inStream, String fileName,String suffix) {
        boolean ret = false;
        fileName = fileName +"."+suffix;
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(suffix));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName,
                    "2020/" + fileName, inStream,
                    objectMetadata);
//            ret = putResult.getETag();
            log.info("上传文件成功 -- Topic:{}", fileName);
            ret = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 删除OSS上的文件
     * @param key 文件名
     * @return 输入流
     */
    public static byte[] downloadFile2OSS(String key,String suffix){
        byte [] result = null;
        key = key + "."+suffix;
        try {
            //初始化
            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, key);
            InputStream in = ossObject.getObjectContent();
            result = FileUtils.inputStream2byte(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * OSS删除文件 (配置生命周期，自动过期。删除方法不试用)
     * @param key 上传时的文件名
     */
    public static void delete(String key) {
        VoidResult voidResult= ossClient.deleteObject(bucketName, key);
    }

    public static List<String> list() {
        // 设置每页列举200个文件。列举所有文件
        final int maxKeys = 200;
        String nextMarker = null;
        List<String> list = new ArrayList<>();
        ObjectListing objectListing;
        do {
            objectListing = ossClient.listObjects(new ListObjectsRequest(bucketName)
                    .withMarker(nextMarker).withMaxKeys(maxKeys));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            for (OSSObjectSummary s : sums) {
                list.add(s.getKey());
                System.out.println(s.getKey());
            }
            nextMarker = objectListing.getNextMarker();
        } while (objectListing.isTruncated());

        return list;
    }

    /**
     * 判断OSS服务文件上传时文件的contentType
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase("pdf")) {
            return "application/pdf";
        }
        return "image/jpeg";
    }
}
